<?php

namespace app\controller;

use app\BaseController;
use think\facade\View;

class bigFile extends BaseController
{

    public function upload($app = '')
    {
        View::assign('app', $app);
        return View::fetch();
    }

    // 上传文件
    public function upFile($app = '', $fileName = '', $chunk = '')
    {
        $path = './upload/' . md5($fileName);
        if (!is_dir($path)) {
            mkdir($path);
        }
        $filename = $path . '/' . $chunk;
        if (!file_exists($filename)) {
            $file = request()->file('fileBlob');
            move_uploaded_file($file->getPathname(), $filename);
        }
        return $this->ok();
    }

    // 合并文件
    public function endFile($app = '', $fileName = '', $chunks = '')
    {
        $chunks = (int)$chunks;
        $path = './upload/' . md5($fileName);
        $filename = './upload/' . $fileName; //合并后的文件名
        if (is_dir($path)) {
            // 文件不存在创建合并
            if (!file_exists($filename)) {
                for ($i = 1; $i <= $chunks; ++$i) {
                    $file = './upload/' . md5($fileName) . '/' . $i; // 读取单个切块
                    $content = file_get_contents($file);
                    unlink($file);
                    if (!file_exists($filename)) {
                        $fd = fopen($filename, "w+");
                    } else {
                        $fd = fopen($filename, "a");
                    }
                    fwrite($fd, $content); // 将切块合并到一个文件上
                }
            }
            rmdir($path);
        }
        return $this->ok($filename);
    }

}